import axios from 'axios'
import { type ToastWrapperInstance } from 'vant'
import useUserStore from '@/stores/user'

export interface BaseResponse {
  status?: number
  code: number
  msg: string
  data: object
}

declare module 'axios' {
  interface AxiosRequestConfig {
    _tipsId?: symbol
    /**
     * 是否校验token
     * @default true
     */
    checkToken?: boolean
  }
}

export const request = axios.create({
  baseURL: import.meta.env.DEV ? __ENV__.VITE_PROXY_BASE_API : __ENV__.VITE_BASE_API,
  timeout: 20_000,
})
const tipsMap = new Map<symbol, ToastWrapperInstance>()

request.interceptors.request.use((config) => {
  config._tipsId = Symbol()
  if (config.checkToken === false) {
    return config
  }
  const userStore = useUserStore()
  const token = userStore.token // 获取 token
  if (!token) {
    console.log('token失效', token)
    userStore.logout()
    // return Promise.reject('no token')
  }
  config.headers.Authorization = `Bearer ${token}`
  config.headers['third-session'] = `${token}`
  // tipsMap.set(config._tipsId, showLoadingToast('请求中...'))
  return config
})

// 业务错误码
const errorCode: Record<number, (data: BaseResponse) => void> = {
  401({ msg }) {
    showFailToast(msg)
    const userStore = useUserStore()
    const token = userStore.token
    if (!token) {
      userStore.logout()
      // return Promise.reject('no token')
    }
  },
  500({ msg }) {
    showFailToast(msg)
  },
}
// http错误码
const httpErrorCode = {
  404() {
    showFailToast('接口不存在')
  },
  413() {
    showFailToast('请求数据过大')
  },
}

// 不要弹出错误信息
request.interceptors.response.use(
  ({ data, config }) => {
    if (config._tipsId) {
      tipsMap.get(config._tipsId)?.close()
      tipsMap.delete(config._tipsId)
    }
    if (data.data instanceof Blob) {
      return data
    }
    const { code } = data
    if (code === 200) {
      return data
    }
    console.log('sssssssssss')
    errorCode[code]?.(data)
    return Promise.reject(data)
  },
  (error) => {
    console.log('error.config', error, error.config)
    tipsMap.get(error.config._tipsId)?.close()
    tipsMap.delete(error.config._tipsId)
    httpErrorCode[error.response?.status as keyof typeof httpErrorCode]?.()
    return Promise.reject(error)
  },
)
